<?php


namespace app\common\controller;

//原生wechat
class Wechat
{
    private $appid = '';
    private $appsecret = '';
    
    public function __construct()
    {

        $this->appid = "";
        $this->appsecret = "";
    }
    
    //获取用户授权信息
    public function getUserOpentId($code = ''){
        //回调地址会传回一个code，根据code去获取openid和授权获取到的access_token
        if(!$code) return [];
        $appid = $this->appid;
        $secret = $this->appsecret;
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        $res = $this->http_curl($url);
        $access_token = $res['access_token'];
        $getopenid = $res['openid'];
        //获取用户授权信息
        $urltoc = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$getopenid."&lang=zh_CN";
        $resinfos = $this->http_curl($urltoc);
        return $resinfos;
    }

    //获取用户授权信息
    public function getOpentId($code = ''){
        //回调地址会传回一个code，根据code去获取openid和授权获取到的access_token
        if(!$code) return [];
        $appid = $this->appid;
        $secret = $this->appsecret;
        $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appid."&secret=".$secret."&code=".$code."&grant_type=authorization_code";
        $res = $this->http_curl($url);
        $getopenid = $res['openid'];
        return $getopenid;
    }
    
    //curl
    public function http_curl($url,$type='get',$res='json',$arr='')
    {
        //1.初始化curl
        $ch = curl_init();
        //2.设置curl的参数
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //不验证证书
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); //不验证证书
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        if ($type == 'post') {
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $arr);
        }
        //3.采集
        $output = curl_exec($ch);
        //4.关闭
        curl_close($ch);
        if ($res == 'json') {
            return json_decode($output, true);
        }
    }
}